from django.shortcuts import render, redirect, reverse
from django.db import connection

cursor = connection.cursor()


def index(request):
    cursor.execute('select * from book')
    rows = cursor.fetchall()
    context = {
        'rows': rows
    }
    return render(request, 'index.html', context=context)


def add_book(request):
    if request.method == 'GET':
        return render(request, 'add_book.html')
    else:
        name = request.POST.get('name')
        author = request.POST.get('author')
        cursor.execute('insert into book set name="%s",author="%s"' % (name, author))
        return redirect(reverse('index'))


def book_detail(request, book_id):
    if request.method == 'GET':
        cursor.execute('select * from book where id=%s' % book_id)
        book = cursor.fetchone()
        context = {
            'book': book
        }
        return render(request, 'book_detail.html', context=context)
    else:
        raise RuntimeError('不支持非GET模式访问')


def delete_book(request):
    if request.method == 'POST':
        book_id = request.POST.get('id')
        cursor.execute('delete from book where id=%s' % book_id)
        return redirect(reverse(viewname='index'))
    else:
        raise RuntimeError('不支持非POST模式访问')
